<?php
declare(strict_types=1);

use think\facade\Config;
use think\facade\Db;
use think\facade\Session;

/**
 * 调试用
 * @param $object
 */
function dd($object){
    echo "<pre>";
    print_r($object);
    die;
}


/**
 * 数组转XML
 *
 * @param array  $data
 * @param string $tag
 *
 * @return string
 */
function array2xml(array $data, string $tag = ''): string
{
    $xml = '';

    foreach ($data as $key => $value) {
        if (is_numeric($key)) {
            if (is_array($value)) {
                $xml .= "<$tag>";
                $xml .= array2xml($value);
                $xml .= "</$tag>";
            } else {
                $xml .= "<$tag>$value</$tag>";
            }
        } else {
            if (is_array($value)) {
                $keys = array_keys($value);
                if (is_numeric($keys[0])) {
                    $xml .= array2xml($value, $key);
                } else {
                    $xml .= "<$key>";
                    $xml .= array2xml($value);
                    $xml .= "</$key>";
                }

            } else {
                $xml .= "<$key>$value</$key>";
            }
        }
    }
    return $xml;
}

/**
 * Xml转数组
 *
 * @param string $xml_string
 *
 * @return array
 */
function xml2array(string $xml_string): array
{
    $targetArray = [];
    $xmlObject = simplexml_load_string($xml_string);
    $mixArray = (array)$xmlObject;
    foreach ($mixArray as $key => $value) {
        if (is_string($value)) {
            $targetArray[$key] = $value;
        }
        if (is_object($value)) {
            $targetArray[$key] = xml2array($value->asXML());
        }
        if (is_array($value)) {
            foreach ($value as $zkey => $zvalue) {
                if (is_numeric($zkey)) {
                    $targetArray[$key][] = xml2array($zvalue->asXML());
                }
                if (is_string($zkey)) {
                    $targetArray[$key][$zkey] = xml2array($zvalue->asXML());
                }
            }
        }
    }
    return $targetArray;

}

/**
 * 生成指定随机数
 *
 * @param int    $length
 * @param string $code
 *
 * @return string
 */
function rand_code(int $length = 4, string $code = ''): string
{
    for ($i = 0; $i < $length; $i++) {         //通过循环指定长度
        $randcode = mt_rand(0, 9);             //指定为数字
        $code .= $randcode;
    }

    return $code;
}

/**
 * 订单号
 *
 * @param int $legth
 *
 * @return string
 */
function build_hash_no(int $legth = 0): string
{
    $yCode = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    return $orderSn = $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr((string)time(), -5) . substr((string)trim(microtime()), 2, 1)  . date('md') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 2);
}

/**
 * Curl请求
 *
 * @param string $url
 * @param array  $request_data
 *
 * @return array
 */
function curl_get_request(string $url, array $request_data = []): array
{
    $curl = curl_init();

    $request_url = http_build_query($request_data);

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url . "?" . $request_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => "GET",
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json'
        ],
    ]);

    $response = curl_exec($curl);

    curl_close($curl);

    if (is_json($response)) {
        return json_decode($response, true);
    }

    return [];
}

/**
 * Curl请求
 *
 * @param string $url
 * @param array  $request_data
 *
 * @return array
 */
function curl_post_request(string $url, array $request_data = [])
{
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => '',
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => json_encode($request_data),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json'
        ],
    ]);

    $response = curl_exec($curl);

    curl_close($curl);

    if ($url != 'http://74.211.103.22:8081/v1/exchange/robot_detail' && $url != 'http://74.211.103.22:8081/v1/exchange/market_price') {
        $insert_object = [
            'action'      => $url,
            'apply_info'  => json_encode($request_data),
            'result_info' => $response,
            'create_time' => date('Y-m-d H:i:s')
        ];
        Db::name('apply_log')->insert($insert_object);
    }

    if (is_json($response)) {
        return json_decode($response, true);
    }

    return [];
}

/**
 * Curl请求
 *
 * @param string $url
 * @param array  $request_data
 *
 * @return array
 */
function curl_post_request_arr(string $url, array $request_data = [])
{
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => '',
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => $request_data
    ]);

    $response = curl_exec($curl);

    curl_close($curl);

    $insert_object = [
        'action'      => $url,
        'apply_info'  => json_encode($request_data),
        'result_info' => $response,
        'create_time' => date('Y-m-d H:i:s')
    ];
    Db::name('apply_log')->insert($insert_object);

    if (is_json($response)) {
        return json_decode($response, true);
    }

    return [];
}


/**
 * CURL请求
 *
 * @param string $url
 * @param array  $data
 *
 * @param string $method
 *
 * @return bool|string
 */
function curl_request_data(string $url = '', string $method = 'POST', array $data = [], array $header = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);

    if (curl_errno($ch)) {
        return false;
    } else {
        return $tmpInfo;
    }
}

/**
 * CURL请求
 *
 * @param string $url
 * @param string $method
 * @param array  $data
 * @param bool   $type
 * @param array  $headers
 * @param bool   $debug
 *
 * @return bool|string
 */
function http_request(string $url, string $method, array $data = [], bool $type = false, array $headers = [], bool $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    //在发起连接前等待的时间，如果设置为0，则无限等待
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60);
    // 设置cURL允许执行的最长秒数
    curl_setopt($ci, CURLOPT_TIMEOUT, 7);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($data)) {
                $tmpdatastr = $type ? json_encode($data) : $data;
                //return $tmpdatastr = $type ? http_build_query($data) : $data;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }

    $ssl = preg_match('/^https:\/\//i', $url) ? true : false;
    curl_setopt($ci, CURLOPT_URL, $url);

    if ($ssl) {
        // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
    }

    // curl_setopt($ci, CURLOPT_HEADER, true) 启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    //  指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    //curl_setopt($ci, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    // curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去
    $response = curl_exec($ci);

    $requestinfo = curl_getinfo($ci);

    curl_getinfo($ci, CURLINFO_HTTP_CODE);

    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($data);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
        exit;
    }

    curl_close($ci);
    return $response;
}

/**
 * 判断是否符合json格式
 *
 * @param $json
 *
 * @return bool
 */
function is_json($json): bool
{
    if (is_bool($json) || empty($json) || is_array($json) || is_object($json) || is_int($json) || is_float($json)) {
        return false;
    }

    return true;
}

/**
 * 日志文件输出
 *
 * @param        $data
 * @param string $title
 * @param string $file
 */
function log_file($data, string $title = "", string $file = "")
{
    // 默认路径
    $path = runtime_path() . "debug/";
    // 创建文件夹
    create_folder($path);

    if (empty($file)) $file = date("Ymd") . ".log";

    // 组合路径
    $file = $path . '/' . $file;

    // 备注
    if ($title) file_put_contents($file, $title . "\n", FILE_APPEND);

    // 打印数据
    if (is_array($data) || is_object($data)) {
        $data = print_r($data, true);
    }

    // 保存日志
    file_put_contents($file, $data . "\n", FILE_APPEND);
}

/**
 * 创建文件夹
 *
 * @param $dirname
 */
function create_folder(string $dirname)
{
    if (!file_exists($dirname)) {
        create_folder(dirname($dirname));
        mkdir($dirname, 0777);
    }
}

/**
 * 简单对称加密算法之加密
 *
 * @param string $string 需要加密的字串
 * @param string $skey   加密EKY
 *
 * @return string|string[]
 */
function encode($string = '', $skey = 'http://www.myzy.com.cn/')
{
    $string = (string)$string;
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key] .= $value;
    return str_replace(['=', '+', '/'], ['O0O0O', 'o000o', 'oo00o'], join('', $strArr));
}

/**
 * 简单对称加密算法之解密
 *
 * @param string $string
 * @param string $skey
 *
 * @return false|string
 */
function decode($string = '', $skey = 'http://www.myzy.com.cn/')
{
    $strArr = str_split(str_replace(['O0O0O', 'o000o', 'oo00o'], ['=', '+', '/'], $string), 2);
    $strCount = count($strArr);

    foreach (str_split($skey) as $key => $value) {
        $key <= $strCount && isset($strArr[$key]) && @$strArr[$key][1] === $value && $strArr[$key] = @$strArr[$key][0];
    }

    return base64_decode(join('', $strArr));
}

/**
 * 隐藏字符串
 *
 * @param string $string
 * @param int    $bengin
 * @param int    $len
 * @param int    $type
 * @param string $glue
 *
 * @return string
 */
function hide_str(string $string = '', $bengin = 0, $len = 4, $type = 0, $glue = "@"): string
{
    $array = [];

    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }

    switch ($type) {
        case 1:
            $array = array_reverse($array);
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", array_reverse($array));
            break;
        case 2:
            $array = explode($glue, $string);
            $array[0] = hide_str($array[0], $bengin, $len, 1);
            $string = implode($glue, $array);
            break;
        case 3:
            $array = explode($glue, $string);
            $array[1] = hide_str($array[1], $bengin, $len, 0);
            $string = implode($glue, $array);
            break;
        case 4:
            $left = $bengin;
            $right = $len;
            $tem = [];
            for ($i = 0; $i < ($length - $right); $i++) {
                if (isset($array[$i]))
                    $tem[] = $i >= $left ? "*" : $array[$i];
            }
            $array = array_chunk(array_reverse($array), $right);
            $array = array_reverse($array[0]);
            for ($i = 0; $i < $right; $i++) {
                $tem[] = $array[$i];
            }
            $string = implode("", $tem);
            break;
        default:
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", $array);
            break;
    }

    return $string;
}

function preg_mobile($mobile)
{
    if (preg_match("/^1[345789]\d{9}$/", $mobile)) {
        return true;
    } else {
        return false;
    }
}


//获取客户端真实ip地址
function get_real_ip(){
    static $realip;
    if(isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }else if(isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip=$_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip=$_SERVER['REMOTE_ADDR'];
        }
    }else{
        if(getenv('HTTP_X_FORWARDED_FOR')){
            $realip=getenv('HTTP_X_FORWARDED_FOR');
        }else if(getenv('HTTP_CLIENT_IP')){
            $realip=getenv('HTTP_CLIENT_IP');
        }else{
            $realip=getenv('REMOTE_ADDR');
        }
    }
    return $realip;
}